package com.example.jobback.service.recruiter.impl;

import com.alibaba.fastjson.JSON;
import com.example.jobback.common.enums.RecruiterType;
import com.example.jobback.config.AuthConfig;
import com.example.jobback.mapper.CompanyMapper;
import com.example.jobback.mapper.InterestMapper;
import com.example.jobback.mapper.PositionMapper;
import com.example.jobback.mapper.RecruiterMapper;
import com.example.jobback.po.Company;
import com.example.jobback.po.Position;
import com.example.jobback.po.Recruiter;
import com.example.jobback.po.User;
import com.example.jobback.req.common.page.PageReq;
import com.example.jobback.req.recruiter.company.profile.CompanyReq;
import com.example.jobback.req.recruiter.employee.create.EmployeeCreatedReq;
import com.example.jobback.req.recruiter.profile.RecruiterReq;
import com.example.jobback.resp.recruiter.company.employee.GetCompanyEmployeeResp;
import com.example.jobback.resp.recruiter.company.message.RCrossComJobMessageResp;
import com.example.jobback.resp.recruiter.company.message.RCrossComMessageResp;
import com.example.jobback.resp.recruiter.company.message.RCrossComUserMessageResp;
import com.example.jobback.resp.recruiter.company.page.RCrossGetPageCompanyListResp;
import com.example.jobback.resp.recruiter.company.page.RCrossGetPageCompanyResp;
import com.example.jobback.resp.recruiter.profile.RecruiterCompanyResp;
import com.example.jobback.result.Result;
import com.example.jobback.service.common.UserCommonService;
import com.example.jobback.service.recruiter.RecruiterCommonService;
import com.example.jobback.service.recruiter.RecruiterCompanyService;
import com.example.jobback.service.seeker.SeekerCrossService;
import com.example.jobback.util.CACHEUtil;
import com.example.jobback.util.PhoneNumberUtils;
import com.example.jobback.util.SecureEncryptionUtil;
import com.example.jobback.util.TLUtil;
import com.example.jobback.websocket.service.MessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.example.jobback.util.RedisConstants.*;

/**
 * @ClassName: RecruiterCompanyServiceImpl
 * @Description:招聘者-公司服务实现类
 * @Author: lhb
 * @Date: 2025/6/21
 */
@Service
public class RecruiterCompanyServiceImpl implements RecruiterCompanyService {


    private final CompanyMapper companyMapper;

    private final CACHEUtil cacheUtil;


    private final RecruiterCommonService recruiterCommonService;

    private final PhoneNumberUtils phoneNumberUtils;

    private final UserCommonService userCommonService;

    private final RecruiterMapper recruiterMapper;

    private final InterestMapper interestMapper;

    private final AuthConfig authConfig;

    private final SeekerCrossService seekerCrossService;

    private final MessageService messageService;

    private final PositionMapper positionMapper;

    public RecruiterCompanyServiceImpl(CACHEUtil cacheUtil, CompanyMapper companyMapper, AuthConfig authConfig, UserCommonService userCommonService, RecruiterMapper recruiterMapper, RecruiterCommonService recruiterCommonService, PositionMapper positionMapper, PhoneNumberUtils phoneNumberUtils, InterestMapper interestMapper, SeekerCrossService seekerCrossService, MessageService messageService) {
        this.cacheUtil = cacheUtil;
        this.companyMapper = companyMapper;
        this.authConfig = authConfig;
        this.userCommonService = userCommonService;
        this.recruiterMapper = recruiterMapper;
        this.recruiterCommonService = recruiterCommonService;
        this.positionMapper = positionMapper;
        this.phoneNumberUtils = phoneNumberUtils;
        this.interestMapper = interestMapper;
        this.seekerCrossService = seekerCrossService;
        this.messageService = messageService;
    }


    /**
     * @Description: 获取公司招聘者基本信息
     * @return Result<RecruiterCompanyResp>
     * @Author lhb
     * @CreateTime 2025/6/21 11:00
     */
    @Override
    public Result<RecruiterCompanyResp> getBasicMessage() {
        //拷贝招聘者个人信息
        Recruiter recruiter= TLUtil.get(TLUtil.R);
        //加工招聘个人信息
        RecruiterCompanyResp resp = processRecruiterBasicMessage(recruiter);
        //电话号码带*处理
        String maskPhone = PhoneNumberUtils.maskPhoneNumber(resp.getPhone());
        resp.setPhone(maskPhone);
        return Result.success(resp);
    }

    /**
     * @Description: 获取指定公司招聘者基本信息,跨服务被调用方，求职端和招聘端使用
     * @param userId
     * @return Result<RecruiterCompanyResp>
     * @Author lhb
     * @CreateTime 2025/6/21 11:04
     */
    @Override
    public Result<RecruiterCompanyResp> getRecruiterBasicMessage(Long userId) {
        Recruiter recruiter=getRecruiterMessage(userId);
        RecruiterCompanyResp resp = processRecruiterBasicMessage(recruiter);
        //电话号码带*处理
        String maskPhone = PhoneNumberUtils.maskPhoneNumber(resp.getPhone());
        resp.setPhone(maskPhone);
        return Result.success(resp);
    }

    /**
     * @Description: 获取招聘者相关信息
     * @param userId
     * @return RecruiterCompanyResp
     * @Author lhb
     * @CreateTime 2025/7/3 21:20
     */
    private Recruiter getRecruiterMessage(Long userId) {
        //在redis查看用户
        String key=RECRUITER_KEY+userId.toString();
        Map<Object,Object> userMap=cacheUtil.getHash(key);
        Recruiter recruiter=null;
        if(userMap.isEmpty()){
            recruiter = recruiterMapper.getRecruiterByUserId(userId);
            if(recruiter == null) {
                throw new IllegalArgumentException("VALIDATION_ERROR：无此用户招聘端信息");
            }
            User user=userCommonService.getUserByUserId(userId);
            BeanUtils.copyProperties(user, recruiter);
        }else {
            // 从 Redis 获取用户 JSON 数据
            String userJson = (String) userMap.get("user");
            //反序列化
            recruiter = JSON.parseObject(userJson, Recruiter.class);
            if(recruiter ==null){
                throw new RuntimeException("缓存查询异常");
            }
        }
        return recruiter;
    }

    /**
     * @Description: 编辑基本信息
     * @param req
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 11:07
     */
    @Override
    public Result<Object> editBasicMessage(RecruiterReq req) {
        Recruiter recruiter=TLUtil.get(TLUtil.R);
        BeanUtils.copyProperties(req, recruiter);
        //修改user的各角色的共同信息
        User user=new User();
        BeanUtils.copyProperties(recruiter, user);
        if(userCommonService.editBasicMessage(user)==0) throw new RuntimeException("修改失败");
        //目前求职者除了共性没有其他信息
        String token = userCommonService.setRedisUser(recruiter,recruiter.getUserId(),RECRUITER_KEY,authConfig.getJwtRecruiterSecret(),RECRUITER_TTL,TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("修改失败");
        return Result.success(token);
    }

    /**
     * @Description: 上传头像
     * @param file
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 11:08
     */
    @Override
    public Result<Object> uploadAvatar(MultipartFile file) {
        Recruiter recruiter=TLUtil.get(TLUtil.R);
        //user对象的userid
        Long userId=recruiter.getUserId();
        String catalog="Avatar/User";
        String lastUrl= userCommonService.uploadAvatar(userId,file,catalog);
        if(lastUrl==null) throw new RuntimeException("上传文件失败");
        if(userCommonService.updateUserAvatar(userId,lastUrl)==0) throw new RuntimeException("上传文件失败");
        recruiter.setAvatar(lastUrl);
        String token = userCommonService.setRedisUser(recruiter,recruiter.getUserId(),RECRUITER_KEY,authConfig.getJwtRecruiterSecret(),RECRUITER_TTL,TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * @Description: 上传公司头像
     * @param file
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 11:08
     */
    @Override
    public Result<Object> uploadCompanyAvatar(MultipartFile file) {
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        boolean equals = recruiter.getType().equals(RecruiterType.BOSS);
        if(!equals) throw new IllegalArgumentException("VALIDATION_ERROR：无权限");
        Long companyId=recruiter.getCompanyId();
        String catalog="Avatar/Company";
        String lastUrl= userCommonService.uploadAvatar(companyId,file,catalog);
        if(lastUrl==null) throw new RuntimeException("上传文件失败");
        if(companyMapper.updateCompanyAvatar(companyId,lastUrl)==0) throw new RuntimeException("上传文件失败");
        Company company=getCompanyMessage(companyId);
        company.setAvatar(lastUrl);
        updateCompanyRedisMessage(company);
        //更新token，延时登录态
        String token=userCommonService.updateRedisUserToken(recruiter.getUserId(),RECRUITER_KEY,authConfig.getJwtRecruiterSecret(),RECRUITER_TTL,TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * @Description: 编辑公司基本信息
     * @param req
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 11:26
     */
    @Override
    public Result<Object> editCompanyBasicMessage(CompanyReq req) {
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        boolean equals = recruiter.getType().equals(RecruiterType.BOSS)||recruiter.getType().equals(RecruiterType.MANAGEMENT);
        if(!equals) throw new IllegalArgumentException("VALIDATION_ERROR：无权限");
        Company company = getCompanyMessage(recruiter.getCompanyId());
        BeanUtils.copyProperties(req, company);
        if(updateCompanyMysqlMessage(company)==0) throw new RuntimeException("修改失败");
        updateCompanyRedisMessage(company);
        //更新token，延时登录态
        String token=userCommonService.updateRedisUserToken(recruiter.getUserId(),RECRUITER_KEY,authConfig.getJwtRecruiterSecret(),RECRUITER_TTL,TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("token生成失败");
        return Result.success(token);
    }

    /**
     * @Description: 编辑公司的关键信息
     * @param companyName
     * @param createDate
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 11:30
     */
    @Override
    public Result<Object> editCompanyCoreMessage(String companyName, LocalDateTime createDate) {
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        boolean equals = recruiter.getType().equals(RecruiterType.BOSS);
        if(!equals) throw new IllegalArgumentException("VALIDATION_ERROR：无权限");
        Long companyId=recruiter.getCompanyId();
        Company company = getCompanyMessage(companyId);
        company.setName(companyName);
        company.setCreateDate(createDate);
        if(companyMapper.editCompanyCoreMessage(companyId,companyName,createDate)==0) throw new RuntimeException("修改失败");
        updateCompanyRedisMessage(company);
        //更新token，延时登录态
        String token=userCommonService.updateRedisUserToken(recruiter.getUserId(),RECRUITER_KEY,authConfig.getJwtRecruiterSecret(),RECRUITER_TTL,TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * @Description: 新增员工
     * @param req
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 11:31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> createEmployee(EmployeeCreatedReq req) {
        Recruiter operator = TLUtil.get(TLUtil.R);
        boolean equals = operator.getType().equals(RecruiterType.BOSS)||operator.getType().equals(RecruiterType.MANAGEMENT);
        if(!equals) throw new IllegalArgumentException("VALIDATION_ERROR：无权限");
        if(req.getType().equals(RecruiterType.BOSS)) throw new IllegalArgumentException("CLIENT_ERROR：不能新增boss的员工");
        String phone = req.getPhone();
        String password=req.getPassword();
        String phoneAes= null;
        String passwordAes=null;
        //加密电话号码
        try {
            phoneAes = SecureEncryptionUtil.encrypt(phone,authConfig.getPhoneSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        User user = userCommonService.getUserByPhoneAes(phoneAes);
        //注册过
        if(Objects.equals(req.getEmployeeCreatedSelect(), 0)) {
            if(Objects.isNull(user)) {
                throw new IllegalArgumentException("VALIDATION_ERROR：该账号无记录");
            }
        } else {
            //新注册
            if(Objects.nonNull(user)) {
                throw new IllegalArgumentException("VALIDATION_ERROR：该账号已有记录");
            }
            //注册
            user = userCommonService.registerUser(phoneAes);
            //加密密码
            try {
                passwordAes = SecureEncryptionUtil.encrypt(password,authConfig.getPasswordSecret());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if(userCommonService.registerUserAuth(user.getUserId(),passwordAes)==0) {
                throw new RuntimeException("注册失败");
            }
        }
        Long userId = user.getUserId();
        Recruiter recruiter=recruiterMapper.getRecruiterByUserId(userId);
        //已经是企业用户不给予注册
        if(Objects.nonNull(recruiter)) {
            throw new IllegalArgumentException("VALIDATION_ERROR：已注册为企业用户");
        }
        recruiter=new Recruiter();
        recruiter.setUserId(userId);
        recruiter.setCompanyId(operator.getCompanyId());
        recruiter.setType(req.getType());
        recruiter.setRole(req.getRole());
        if(recruiterMapper.register(recruiter)==0) {
            throw new RuntimeException("注册失败");
        }
        //更新token，延时登录态
        String token=userCommonService.updateRedisUserToken(operator.getUserId(),RECRUITER_KEY,authConfig.getJwtRecruiterSecret(),RECRUITER_TTL,TimeUnit.DAYS);
        return Result.success(token);
    }

    /**
     * @Description: 跨服务被调用方，获取指定公司信息
     * @param companyId
     * @return Result<RCrossCompanyBasicMessage>
     * @Author lhb
     * @CreateTime 2025/6/25 9:11
     */
    @Override
    public Result<RCrossComMessageResp> CrossGetCompanyMessageForAdmin(Long companyId) {
        RCrossComMessageResp resp=new RCrossComMessageResp();
        Company company = getCompanyMessage(companyId);
        if(company==null) throw new IllegalArgumentException("VALIDATION_ERROR：无此公司信息");
        BeanUtils.copyProperties(company,resp);
        resp.setRCrossComJobMessageRespList(new ArrayList<>());
        resp.setRCrossComUserMessageRespList(new ArrayList<>());
        List<Recruiter> recruiterList=recruiterMapper.getRecruitersByCompanyId(company.getCompanyId());
        //获取userIds
        List<Long> userIds = recruiterList.stream()
                .map(Recruiter::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<User> userList = userCommonService.getUsersByUserIds(userIds);
        //构建 userId -> User 的映射
        Map<Long, User> userMap = userList.stream()
                .collect(Collectors.toMap(
                        User::getUserId,
                        Function.identity()
                ));
        //遍历 recruiterList，填充 Recruiter 属性
        recruiterList.forEach(recruiter -> {
            User user = userMap.get(recruiter.getUserId());
            if (user != null) {
                BeanUtils.copyProperties(user,recruiter);
            }
        });
        List<Position>  positionList= positionMapper.getPositionByCompanyId(company.getCompanyId());
        if(!recruiterList.isEmpty()){
            //映射员工字段
            List<RCrossComUserMessageResp> userRespList = recruiterList.stream()
                    .map(recruiter -> {
                        RCrossComUserMessageResp userResp = new RCrossComUserMessageResp();
                        BeanUtils.copyProperties(recruiter,userResp);
                        try {
                            userResp.setPhone(phoneNumberUtils.decryptPhone(recruiter.getPhoneAes()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        return userResp;
                    })
                    .toList();
            resp.setRCrossComUserMessageRespList(userRespList);
            //根据userId设置map对象
            Map<Long, RCrossComUserMessageResp> rCrossComUserMessageRespMap = userRespList.stream()
                    .collect(Collectors.toMap(
                            RCrossComUserMessageResp::getUserId,
                            Function.identity()
                    ));
            //映射职位字段
            if (!positionList.isEmpty()) {
                List<RCrossComJobMessageResp> jobRespList = positionList.stream()
                        .map(position -> {
                            RCrossComJobMessageResp jobResp = new RCrossComJobMessageResp();
                            BeanUtils.copyProperties(position,jobResp);
                            jobResp.setRCrossComUserMessageResp(rCrossComUserMessageRespMap.get(position.getUserId()));
                            return jobResp;
                        })
                        .collect(Collectors.toList());

                resp.setRCrossComJobMessageRespList(jobRespList);
            }
        }
        return Result.success(resp);
    }

    /**
     * @Description:获取公司招聘者基本信息，跨服务被调用方，管理员端调用
     * @param userId
     * @return Result<RecruiterCompanyResp>
     * @Author lhb
     * @CreateTime 2025/7/3 21:13
     */
    @Override
    public Result<RecruiterCompanyResp> getRecruiterBasicMessageForAdmin(Long userId) {
        Recruiter recruiter=getRecruiterMessage(userId);
        RecruiterCompanyResp resp = processRecruiterBasicMessage(recruiter);
        return Result.success(resp);
    }



    /**
     * @Description: 获取公司列表，跨服务，被调用方
     * @param pageReq
     * @return Result<RCrossGetPageCompistResp>
     * @Author lhb
     * @CreateTime 2025/7/4 15:19
     */
    @Override
    public Result<RCrossGetPageCompanyListResp> getCompanyList(PageReq pageReq) {
        String content=pageReq.getContent();
        int page = pageReq.getPage();
        int size = pageReq.getSize();
        System.out.println("测试搜索内容:"+content);
        List<Company> companyList;
        if(content.isEmpty()){
            PageHelper.startPage(page, size);
            companyList=companyMapper.getCompanyList();
        }else {
            PageHelper.startPage(page, size);
            companyList=companyMapper.getCompanyListByName(content);
        }
        if(companyList==null ||companyList.isEmpty()){
            RCrossGetPageCompanyListResp resp = new RCrossGetPageCompanyListResp();
            resp.setPages(0);
            resp.setTotal(0L);
            resp.setPageNum(0);
            resp.setPageSize(0);
            resp.setSize(0);
            resp.setRespList(new ArrayList<>());
            return Result.success(resp);
        }
        //获取页的相关信息
        PageInfo<Company> companyPageInfo= new PageInfo<>(companyList);
        //处理分页查询管理员列表响应体
        RCrossGetPageCompanyListResp resp = processPageCompanyList(companyList,companyPageInfo);
        return Result.success(resp);
    }

    /**
     * @Description: 获取公司员工列表
     * @return Result<List<GetCompanyEmployeeResp>>
     * @Author lhb
     * @CreateTime 2025/7/9 9:38
     */
    @Override
    public Result<List<GetCompanyEmployeeResp>> getCompanyEmployees() {
        List<GetCompanyEmployeeResp> respList=new ArrayList<>();
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        Long companyId=recruiter.getCompanyId();
        List<Recruiter> recruiterList = recruiterMapper.getRecruitersByCompanyId(companyId);
        //获取userIds
        List<Long> userIds = recruiterList.stream()
                .map(Recruiter::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<User> userList = userCommonService.getUsersByUserIds(userIds);
        //构建 userId -> User 的映射
        Map<Long, User> userMap = userList.stream()
                .collect(Collectors.toMap(
                        User::getUserId,
                        Function.identity()
                ));
        //遍历 recruiterList，填充 resp 属性
        recruiterList.forEach(recruiterElem -> {
            User user = userMap.get(recruiterElem.getUserId());
            GetCompanyEmployeeResp resp=new GetCompanyEmployeeResp();
            if (user != null) {
                BeanUtils.copyProperties(recruiterElem,resp);
                BeanUtils.copyProperties(user,resp);
                Long age=0L;
                LocalDateTime birthDate = user.getBirthDate();
                if (birthDate!=null) {
                    age = (long) Period.between(LocalDate.from(birthDate), LocalDate.now()).getYears();
                }
                resp.setAge(age);
                String maskedPhone="";
                try {
                    maskedPhone=phoneNumberUtils.decryptPhone(user.getPhoneAes());
                    maskedPhone=PhoneNumberUtils.maskPhoneNumber(maskedPhone);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                resp.setPhone(maskedPhone);
            }
            respList.add(resp);
        });
        return Result.success(respList);
    }

    /**
     * @Description: 删除员工
     * @param deleteUserId 
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/26 17:20
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> deleteEmployee(Long deleteUserId) {
        //id为6测试，发布个变更redis未插入
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        if(!Objects.equals(recruiter.getType(), RecruiterType.BOSS)) {
            //如果不是老板，无权限删除
            throw new IllegalArgumentException("VALIDATION_ERROR：无权限");
        }
        if(Objects.equals(recruiter.getUserId(), deleteUserId)) {
            //不能删除BOSS
            throw new IllegalArgumentException("VALIDATION_ERROR：不能删除BOSS");
        }
        Recruiter deleteRecruiter = recruiterMapper.getRecruiterByUserId(deleteUserId);
        Long deleteRecruiterCompanyId = deleteRecruiter.getCompanyId();
        if(Objects.isNull(deleteRecruiter)) {
            throw new NullPointerException("员工不存在");
        }
        if(!Objects.equals(recruiter.getCompanyId(), deleteRecruiterCompanyId)) {
            //非本公司成员
            throw new IllegalArgumentException("VALIDATION_ERROR：无权限");
        }
        //删除角色和感兴趣数据
        recruiterMapper.deleteRecruiterById(deleteUserId);
        interestMapper.deleteByRecruiterId(deleteUserId);
        //删除投递和收藏数据
        seekerCrossService.deleteDeliverByRecruiterUserId(deleteUserId);
        List<Long> positionIdList = positionMapper.getPositionIdsByUserId(deleteUserId);
        if(!positionIdList.isEmpty()) {
            //非空删除收藏数据
            seekerCrossService.deleteCollectByPositionIds(positionIdList);
        }
        //因为外键约束，最后删除岗位表
        positionMapper.deletePositionsByUserId(deleteUserId);
        //删除聊天记录，并且关闭websocket连接，管理的删除功能也需要做到这一步
        messageService.clearUserMessageRecord(deleteUserId, messageService.recruiterRole);
        //删除redis数据
        recruiterCommonService.deleteRecruiterPubPositionsRedis(deleteUserId, deleteRecruiterCompanyId);
        recruiterCommonService.deleteRecruiterUpdatePositionsRedis(deleteUserId, deleteRecruiterCompanyId);
        cacheUtil.deleteKeySafely(RECRUITER_KEY+deleteUserId);
        //更新token，延时登录态
        String token=userCommonService.updateRedisUserToken(
                recruiter.getUserId(),RECRUITER_KEY,authConfig.getJwtRecruiterSecret(),RECRUITER_TTL,TimeUnit.DAYS);
        if(Objects.isNull(token)) {
            throw new RuntimeException("生成token失败");
        }
        return Result.success(token);
    }

    /**
     * @Description: 处理分页查询公司列表响应体
     * @param companyList
     * @param companyPageInfo 
     * @return RCrossGetPageCompanyListResp
     * @Author lhb
     * @CreateTime 2025/7/4 14:39
     */
    private RCrossGetPageCompanyListResp processPageCompanyList(List<Company> companyList,
                                                                PageInfo<Company> companyPageInfo) {
        RCrossGetPageCompanyListResp resp=new RCrossGetPageCompanyListResp();
        resp.setRespList(new ArrayList<>());
        resp.setPages(companyPageInfo.getPages());
        resp.setTotal(companyPageInfo.getTotal());
        resp.setPageNum(companyPageInfo.getPageNum());
        resp.setPageSize(companyPageInfo.getPageSize());
        resp.setSize(companyPageInfo.getSize());
        for (Company company:companyList){
            RCrossGetPageCompanyResp rCrossGetPageCompanyResp=new RCrossGetPageCompanyResp();
            BeanUtils.copyProperties(company,rCrossGetPageCompanyResp);
            resp.getRespList().add(rCrossGetPageCompanyResp);
        }
        return resp;
    }


    /**
     * @Description: 加工招聘者及关联公司的基本信息
     * @param recruiter
     * @return RecruiterCompanyResp
     * @Author lhb
     * @CreateTime 2025/6/21 11:00
     */
    private RecruiterCompanyResp processRecruiterBasicMessage(Recruiter recruiter){
        String phone = null;
        try {
            phone = SecureEncryptionUtil.decrypt(recruiter.getPhoneAes(), authConfig.getPhoneSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        RecruiterCompanyResp resp=new RecruiterCompanyResp();
        resp.setPhone(phone);
        //计算年龄
        Long age=0L;
        LocalDateTime birthDate=recruiter.getBirthDate();
        if (birthDate!=null) {
            age = (long) Period.between(LocalDate.from(birthDate), LocalDate.now()).getYears();
        }
        resp.setAge(age);
        //查找公司信息
        Long companyId=recruiter.getCompanyId();
        Company company=getCompanyMessage(companyId);
        if(company!=null){
            //如果company为null，返回的就是一堆空值
            BeanUtils.copyProperties(company, resp);
            resp.setCompanyName(company.getName());
            resp.setCompanyAvatar(company.getAvatar());
            resp.setCompanyLocation(company.getLocation());
        }
        //个人信息最后拷贝
        BeanUtils.copyProperties(recruiter, resp);
        return resp;
    }


    /**
     * @Description: 获取公司基本信息
     * @param companyId
     * @return Company
     * @Author lhb
     * @CreateTime 2025/6/21 11:01
     */
    public Company getCompanyMessage(Long companyId){
        return recruiterCommonService.getCompanyMessage(companyId);
    }


    /**
     * @Description: 修改在redis中的公司信息
     * @param company
     * @return void
     * @Author lhb
     * @CreateTime 2025/6/21 11:10
     */
    private void updateCompanyRedisMessage(Company company) {
        String key=COMPANY_KEY+company.getCompanyId().toString();
        Map<String, Object> companyData = new HashMap<>();
        String companyStoreJson = JSON.toJSONString(company);
        companyData.put("company", companyStoreJson);
        cacheUtil.setHash(key,companyData,COMPANY_TTL,TimeUnit.DAYS);
    }

    /**
     * @Description: 修改在mysql的公司信息
     * @param company
     * @return int
     * @Author lhb
     * @CreateTime 2025/6/21 11:30
     */
    private int updateCompanyMysqlMessage(Company company) {
        return companyMapper.updateCompany(company);
    }
}
